package org.ipb.controller.login;

import java.util.Map;

import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;
import org.ipb.model.PenggunaSistem;

import com.opensymphony.xwork2.ActionSupport;

import util.hibernate.DAO;
import util.secure.Enkripsi;

public class Authentikasi extends ActionSupport implements SessionAware {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private String password;
	private String userName;
	private String home;
	private String controller;
	private SessionMap<String, Object> session;

	public String execute() {
		DAO<Integer> dao = new DAO<Integer>();
		dao.createCriteria(PenggunaSistem.class);
		Enkripsi enkripsi = new Enkripsi();

		if (!getUserName().equals("su")) {

			dao.addFilter("eq", "userName", getUserName());
			dao.addFilter("eq", "password", enkripsi.md5(getPassword()));
			System.out.println(enkripsi.md5(getPassword()));

			PenggunaSistem penggunaSistem = (PenggunaSistem) dao.findUnique();
			// System.out.println(penggunaSistem.getKelompokPengguna().getRootUrl());
			if (penggunaSistem != null) {
				session.put("userLevel", 1);
				session.put("group", penggunaSistem.getKelompokPengguna()
						.getRootUrl());
				session.put("userId", penggunaSistem.getId());
				session.put("userName", penggunaSistem.getUserName());
				session.put("loginState", true);
				dao.close();
				return SUCCESS;
			} else {
				dao.close();
				return LOGIN;
			}
		} else {
			if (getPassword().equals("ff")) {
				
				session.put("userLevel", 0);
				session.put("group", "su");
				session.put("userName", "su");
				session.put("userId", "0");
				session.put("loginState", true);
				dao.close();
				return SUCCESS;
			} else {
				dao.close();
				return LOGIN;
			}
		}
	}

	public String logout() {
		session.invalidate();
		return SUCCESS;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public SessionMap<String, Object> getSession() {
		return session;
	}

	public String getHome() {
		return home;
	}

	public void setHome(String home) {
		this.home = home;
	}

	public void setSession(Map<String, Object> map) {
		this.session = (SessionMap<String, Object>) map;
	}

	public String getUserName() {
		return userName;
	}

	public void setUserName(String userName) {
		this.userName = userName;
	}

	public String getController() {
		return controller;
	}

	public void setController(String controller) {
		this.controller = controller;
	}

}
